﻿#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include "QFile"
#include "QFileDialog"
#include <QDateTime>
#include <QtDebug>
#include <QSettings>
#include <QMessageBox>
#include <QDir>
#include <QSqlRecord>

#define cout qDebug()<< __FILE__ << " " << __LINE__ <<":"


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    hz.clear();
    en.clear();
    wc.clear();
    num.clear();

    QStringList drv = QSqlDatabase::drivers();
    qDebug()<<drv;
    db = QSqlDatabase::addDatabase("QSQLITE");
    QString local_path_database = "./Database/dictionary_ll.db";
    QString remote_path_database = "//ccnqhn01/15制造中心/01中心通用文件/27语料库/Dictionary/Database/dictionary_ll.db";
    QDir dir("./");
    if ( dir.exists("Database") == false )
    {
        if ( dir.mkdir( "Database" ) == false )
        {
             cout<<"mkdir Database fail";
        }
    }
#if 1
    QSettings settings("./cfg.ini", QSettings::IniFormat );
    settings.setIniCodec("UTF-8");
    QStringList list = settings.childGroups();
    if ( list.contains("remotePath") == false )
    {
        settings.beginGroup("remotePath");
        settings.setValue("path", remote_path_database );
        settings.endGroup();
        settings.sync();
    }
    settings.beginGroup("remotePath");
    remote_path_database = settings.value( "path" ).toString();
    settings.endGroup();
    cout<<"远程数据库路径："<<remote_path_database;
    QFileInfo remoteDataBaseInfo( remote_path_database );
    if ( remoteDataBaseInfo.isFile() )
    {
        QFileInfo localDataBaseInfo( local_path_database );
        if ( remoteDataBaseInfo.lastModified().toMSecsSinceEpoch() > localDataBaseInfo.lastModified().toMSecsSinceEpoch() )
        {
            int  Button_value =  QMessageBox::warning(this, "警告：", "是否更新本地数据库?", QMessageBox::Button::Ok, QMessageBox::Button::Cancel ) ;
            if ( Button_value == QMessageBox::Button::Ok )
            {
                copyFile( remote_path_database, local_path_database, true );
                ui->tEd_result->append("更新本地数据库");
            }
            else
            {
                ui->tEd_result->append("用户取消更新");
            }
        }
        else
        {
            qDebug()<<"不需要更新";
        }
    }
    else
    {
        ui->tEd_result->append("远程数据库不存在" );
    }
#endif
    db.setDatabaseName( local_path_database );
    if ( !db.open() )
    {
        qDebug()<<"open err"<<db.lastError();
        qDebug()<<"open err"<<db.lastError().driverText();
    }
    query = new QSqlQuery();
    QString sqlSelect = "select * from dictionary;";
    if ( !query->exec( sqlSelect ) )
    {
        qDebug()<<"select data error ";
        ui->tEd_result->append("QSqlDatabase read fail");
    }
    /*查询词性列，以做兼容*/
    if ( query->record().contains("WordClass") == false )
    {
        /* add new colomn */
        QString sqlAddColumnTable = QString( "alter table dictionary add column WordClass TEXT;" );
        if ( !query->exec( sqlAddColumnTable ) )
        {
            qDebug()<<sqlAddColumnTable;
            qDebug()<<"sqlAddColumnTable"<<db.lastError();
            qDebug()<<"sqlAddColumnTable"<<db.lastError().text();
        }
    }
    sqlSelect = "select * from dictionary;";
    if ( !query->exec( sqlSelect ) )
    {
        qDebug()<<"select data error ";
        ui->tEd_result->append("QSqlDatabase read fail");
    }
    QString str;
    uint16_t cnt = 1 ;
    while ( query->next() )
    {
        num.append( QString::number( cnt++ ) + "." );
        str = query->value("Chinese").toString();
        hz.append(str);
        str = query->value("English").toString();
        en.append(str);
        str = query->value("WordClass").toString();
        wc.append(str);
    }
    if ( db.isOpen() == true )
    {
        db.close();
    }
    ui->tEd_result->append("QSqlDatabase num:" + QString::number( hz.count() ) );
    connect( ui->pBt_start, &QPushButton::clicked   , this, &Widget::start_translate );
}

Widget::~Widget()
{
    if ( query != nullptr )
    {
        delete query;
        query = nullptr ;
    }
    if ( db.isOpen() )
    {
        db.close();
        qDebug()<<"db.close()";
    }
    delete ui;
}

void Widget::start_translate()
{
    if ( Language == _ENGLISH )
    {
        Language = _CHINESE ;
        ui->pBt_start->setText("中文");
    }
    else
    {
        Language = _ENGLISH ;
        ui->pBt_start->setText("英文");
    }
    ui->tEd_result->clear();
}

void Widget::get_file_path()
{
//    QString filepath = QFileDialog::getOpenFileName( this, "Save File", QString("hello world"), "xlsx(*.xlsx);;所有文件(*.*)" );
    //    ui->lEd_file_path->setText( filepath );
}

void Widget::translate_Chinese()
{
    bool is_find = false ;
    QString str = ui->lEd_input->text();
    if ( str.count() == 0 )
    {
        return;
    }
    QString perfect_match;
    QString fuzzy_match;

    fuzzy_match.clear();
    perfect_match.clear();
    ui->tEd_result->clear();

    for ( int i=0; i<hz.count(); i++ )
    {
        if ( hz[i].compare( str ) == 0 )
        {
            is_find = true ;
            perfect_match += num[i] + " " + en[i] + " " + wc[i] + " " + hz[i] + "\r\n"  ;
        }
        else if ( hz[i].contains( str ) == true )
        {
            is_find = true ;
            fuzzy_match += num[i] + " " + en[i] + " " + wc[i] + " " + hz[i] + "\r\n"  ;
        }
    }
    if ( is_find == false )
    {
        ui->tEd_result->append( "未找到相关词条..." );
    }
    else
    {
        if ( perfect_match.count() > 0 )
        {
            ui->tEd_result->append( "最佳词条:" );
            ui->tEd_result->append( perfect_match );
        }
        if ( fuzzy_match.count() > 0 )
        {
            ui->tEd_result->append( "模糊词条:" );
            ui->tEd_result->append( fuzzy_match );
        }
    }
}

void Widget::translate_English()
{
    bool is_find = false ;
    QString str = ui->lEd_input->text();
    if ( str.count() == 0 )
    {
        return;
    }
    QString perfect_match;
    QString fuzzy_match;

    fuzzy_match.clear();
    perfect_match.clear();
    ui->tEd_result->clear();

    for ( int i=0; i<en.count(); i++ )
    {
        if ( en[i].compare( str ) == 0 )
        {
            is_find = true ;
            perfect_match += num[i] + " " + en[i] + " " + wc[i] + " " + hz[i] + "\r\n"  ;
        }
        else if ( en[i].contains( str ) == true )
        {
            is_find = true ;
            fuzzy_match += num[i] + " " + en[i] + " " + wc[i] + " " + hz[i] + "\r\n"  ;
        }
    }
    if ( is_find == false )
    {
        ui->tEd_result->append( "未找到相关词条..." );
    }
    else
    {
        if ( perfect_match.count() > 0 )
        {
            ui->tEd_result->append( "最佳词条:" );
            ui->tEd_result->append( perfect_match );
        }
        if ( fuzzy_match.count() > 0 )
        {
            ui->tEd_result->append( "模糊词条:" );
            ui->tEd_result->append( fuzzy_match );
        }
    }
}

void Widget::on_lEd_input_textChanged(const QString &arg1)
{
    qDebug()<<arg1;
    if ( arg1.count() > 0 )
    {
        if ( Language == _ENGLISH )
        {
            translate_English();
        }
        else
        {
            translate_Chinese();
        }
    }
    else
    {
        ui->tEd_result->clear();
    }
}

bool Widget::copyFile(QString srcPath, QString dstPath, bool coverFileIfExist)
{
    srcPath.replace("\\", "/");
    dstPath.replace("\\", "/");
    if (srcPath == dstPath) {
        return true;
    }
    if (!QFile::exists(srcPath)) {  //源文件不存在
        return false;
    }
    if (QFile::exists(dstPath)) {
        if (coverFileIfExist) {
            QFile::remove(dstPath);
        }
    }
    if (!QFile::copy(srcPath, dstPath)){
        return false;
    }
    return true;
}

